package com.rayboo.example.collections.map;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;

/**
 * 同步HashMap示例
 *
 * @author ray
 * @since 2019/07/25
 *
 * <p>HashMap是一个非同步的集合类。如果我们需要对它执行线程安全操作，那么我们必须明确地同步它。
 *
 * <p>https://beginnersbook.com/2013/12/how-to-synchronize-hashmap-in-java-with-example/
 */
public class HashMapSyncExample {

    public static void main(String args[]) {
        HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
        hashMap.put(2, "Anil");
        hashMap.put(44, "Ajit");
        hashMap.put(1, "Brad");
        hashMap.put(4, "Sachin");
        hashMap.put(88, "XYZ");

        Map map = Collections.synchronizedMap(hashMap);
        Set set = map.entrySet();
        synchronized (map) {
            Iterator i = set.iterator();
            // Display elements
            while (i.hasNext()) {
                Map.Entry me = (Map.Entry) i.next();
                System.out.print(me.getKey() + ": ");
                System.out.println(me.getValue());
            }
        }
    }
}
